﻿using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System;
using SGLL.Properties;

namespace SGLL
{
    class ClassFunctions
    {
        public enum Filters
        {
            Alphanumeric,
            Decimal,
            Number
        }
        public static bool TextInputFilter(Filters filter, char key)
        {
            switch (filter)
            {
                case Filters.Alphanumeric:
                    return key == 8 || (key >= 32 && key <= 38) || (key >= 40 && key <= 127) || key == 201 || key == 205 || key == 211 || key == 218 || key == 225 || key == 233 || key == 237 || key == 243 || key == 250 || key == 252 || key == 209 || key == 241 || key == 220;
                case Filters.Decimal:
                    return (key >= 48 && key <= 57) || key == 8 || key == 46;
                case Filters.Number:
                    return (key >= 48 && key <= 57) || key == 8;
                default:
                    return false;
            }
        }
        private static SqlConnection GetNewConnection()
        {
            //return new SqlConnection(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed ? Properties.Settings.Default.ConnectionStringMP : Properties.Settings.Default.ConnectionString);
            return new SqlConnection(Settings.Default.ConnectionString);
        }
        public static void Populate(ComboBox comboBox, string sqlQuery)
        {
            comboBox.DataSource = GetData(sqlQuery);
            comboBox.ValueMember = "ID";
            comboBox.DisplayMember = "DESCRIPTION";
            comboBox.SelectedIndex = -1;
        }
        public static void Populate(CheckedListBox checkedListBox, string sqlQuery)
        {
            checkedListBox.DataSource = GetData(sqlQuery);
            checkedListBox.ValueMember = "ID";
            checkedListBox.DisplayMember = "DESCRIPTION";
        }
        public static void Populate(DataGridView dataGridView, string sqlQuery)
        {
            dataGridView.DataSource = GetData(sqlQuery);
            
            //dataGridView.data
            //dataGridView.bind
            //dataGridView.DataBind();
        }
        /// <summary>
        /// Read data from the Database given a SqlQuery
        /// </summary>
        /// <param name="sqlQuery">Query to be executed against the database</param>
        /// <returns>DataTable</returns>
        public static DataTable GetData(string sqlQuery)
        {
            DataTable dataTable = new DataTable();
            using (SqlConnection sqlConnection = GetNewConnection())
            {
                sqlConnection.Open();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlQuery, sqlConnection);
                dataAdapter.Fill(dataTable);
                return dataTable;
            }
        }
        /// <summary>
        /// Read data from the Database given a SqlQuery
        /// </summary>
        /// <param name="sqlQuery">Query to be executed against the database</param>
        /// <returns>Object</returns>
        public static object GetSingleData(string sqlQuery)
        {
            using (SqlConnection sqlConnection = GetNewConnection())
            {
                SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
                sqlConnection.Open();
                return sqlCommand.ExecuteScalar(); 
            }
        }
        /// <summary>
        /// Write Data to the DataBase given a SqlQuery and Parameters
        /// </summary>
        /// <param name="sqlQuery">Query to be executed against the database</param>
        /// <param name="arguments">The parameters on the query</param>
        /// <returns>Number of rows affected</returns>
        public static int SetData(string sqlQuery, object[] arguments)
        {
            using (SqlConnection sqlConnection = GetNewConnection())
            {
                SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
                //Substitute the arguments
                for (int i = 0; i < arguments.Length; i++) sqlCommand.Parameters.AddWithValue(string.Format("@{0}", i), arguments[i]);
                //Check for nulls
                foreach (IDataParameter parameter in sqlCommand.Parameters) if (parameter.Value == null) parameter.Value = DBNull.Value;
                //Open the connection to the database
                sqlConnection.Open();
                //Execute the Query
                return sqlCommand.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// Send a email with the error generated with the Application
        /// </summary>
        /// <param name="subject">Context of the mail </param>
        /// <param name="body">Error message</param>
        /// <param name="to">Email </param>
        public static void SendMail(string to, string subject, string body)
        {
            try
            {
                //Validations
                if (string.IsNullOrEmpty(Settings.Default.Email)) throw new Exception("Correo Electrónico vacío en Configuración del Sistema");
                if (string.IsNullOrEmpty(Settings.Default.Password)) throw new Exception("Contraseña de Correo Electrónico vacía en Configuración del Sistema");
                //Coding
                MailMessage message = new MailMessage {From = new MailAddress(Settings.Default.Email, "Medipath")};
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true;
                SmtpClient client = new SmtpClient("smtp.gmail.com")
                                        {
                                            EnableSsl = true,
                                            UseDefaultCredentials = false,
                                            Credentials =
                                                new NetworkCredential(Settings.Default.Email,
                                                                      Settings.Default.Password)
                                        };
                client.Send(message);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, Resources.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
        public static void ErrorLog(Exception error)
        {
            SendMail
            (
                "emilio_ivanovich@hotmail.com",
                string.Format("[SGLL] Error - {0}", DateTime.Now), 
                string.Format("Message: {1}{0}Source: {2}{0}TargetSite: {3}{0} StackTrace: {4}", "<br/>", error.Message, error.Source, error.TargetSite.Name, error.StackTrace)
            );
        }
        public static string GetLastCall()
        {
            return string.Format(Resources.toolStripStatusLabelLastCall, GetSingleData(ClassSQL.GetLastCall));
        }
        public static string GetTotalCalls()
        {
            int calls = (int)ClassFunctions.GetSingleData(ClassSQL.GetNumberOfCallsToday);
            return string.Format(Resources.toolStripStatusLabelCalls, calls, calls > 1 ? "s" : string.Empty);
        }
        public static bool CheckIfExists(string sqlQuery)
        {
            using (SqlConnection sqlConnection = GetNewConnection())
            {
                SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
                sqlConnection.Open();
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    return sqlDataReader.Read();
                }
            }
        }
    }
}